<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: 'index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 头部警告区域 -->
      <el-alert
        title="注意：只允许第三级分类设置相关参数！！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cateStyle">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader
            v-model="selectCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
    </el-card>
    <!-- tab -->
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="动态参数" name="many">
        <el-button
          type="primary"
          size="mini"
          :disabled="isButtonShow"
          @click="addDialogValue = true"
          >添加参数</el-button
        >
        <template>
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand"></el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-tab-pane>
      <el-tab-pane label="静态属性" name="only">
        <el-button
          type="primary"
          size="mini"
          :disabled="isButtonShow"
          @click="addDialogValue = true"
          >添加属性</el-button
        >
        <template>
          <el-table :data="onlyTabkeData" border stripe  style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-row
                  v-for="(item, key) in scope.row.attr_vals"
                  :key="key"
                  style="width: 100%"
                >
                  <el-tag>{{ item }}</el-tag>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button type="danger" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-tab-pane>
    </el-tabs>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogValue"
      width="50%"
    >
      <el-form
        :model="addFrom"
        :rules="addFromRules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogValue = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogValue"
      width="50%"
    >
      <el-form
        :model="editFrom"
        :rules="editFromRules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogValue = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类
      cateList: [],
      // 联机选择器
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 联级选择器双向绑定数组
      selectCateKeys: [],
      // 被激活的页签
      activeName: "many",
      // 动态属性
      manyTableData: [],
      // 静态属性
      onlyTabkeData: [],
      // 控制添加对话框显示与隐藏
      addDialogValue: false,
      // 添加表单数据对象
      addFrom: {
        attr_name: "",
      },
      addFromRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      // 修改对话框
      editDialogValue: false,
      editFrom: {},
      editFromRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取所有商品分类
    async getCateList() {
      await this.$Req.get("/categories").then((res) => {
        const { data, meta } = res.data;
        if (meta.status !== 200) {
          return this.$message.error("获取商品分类失败！");
        }
        this.cateList = data;
      });
    },
    handleChange() {
      this.getParamsData();
    },
    async getParamsData() {
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = [];
        return;
      }

      // 根据所选获取分类

      await this.$Req
        .get(`/categories/${this.cateId}/attributes`, {
          params: { sel: this.activeName },
        })
        .then((res) => {
          const { data, meta } = res.data;

          if (this.activeName === "many") {
            this.manyTableData = data;
          } else {
            this.onlyTabkeData = data;
          }
          data.forEach((item) => {
            item.attr_vals = item.attr_vals.split(",");
          });
          console.log(data);
        });
    },
    handleTabClick() {
      this.getParamsData();
    },
    // 监听添加对话框关闭事件
    // addDialogClosed(){
    //   this.$refs.addFrom.resetFields()
    // }
    // 添加动态和静态属性
    async addParams() {
      await this.$Req
        .post(`/categories/${this.cateId}/attributes`, {
          attr_name: this.addFrom.attr_name,
          attr_sel: this.activeName,
        })
        .then((res) => {
          this.getParamsData();
          this.addDialogValue = false;
          const { data, meta } = res.data;

          if (meta.status === 201) {
            this.$message({
              type: "success",
              message: meta.msg,
            });
          }
        });
    },

    showEditDialog(rowId) {
      // 查询当前参数
      this.$Req
        .get(`categories/${this.cateId}/attributes/${rowId}`, {
          params: { attr_sel: this.activeName },
        })
        .then((res) => {
          const { data, meta } = res.data;

          if (meta.status !== 200) {
            this.$message({
              type: "error",
              message: meta.msg,
            });
          }
          this.editFrom = data;
        });
      this.editDialogValue = true;
    },
    // 点击按钮修改参数
    editParams() {
      this.$Req
        .put(`categories/${this.cateId}/attributes/${this.editFrom.attr_id}`, {
          attr_name: this.editFrom.attr_name,
          attr_sel: this.activeName,
        })
        .then((res) => {
          this.getParamsData();
          this.editDialogValue = false;
          const { data, meta } = res.data;

          if (meta.status === 200) {
            this.$message({
              type: "success",
              message: meta.msg,
            });
          }
        });
    },
    // 删除参数
    async removeParams(rowIdValue) {
      await this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$Req
            .delete(`/categories/${this.cateId}/attributes/${rowIdValue}`)
            .then((res) => {
              this.getParamsData();
              console.log(res);
            });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  // 计算属性
  computed: {
    // 按钮监听
    isButtonShow() {
      if (this.selectCateKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 当前选中的三级分类id
    cateId() {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2];
      }
      return null;
    },
    // 动态计算参数面板
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态参数";
    },
  },
};
</script>

<style>
.el-main {
  line-height: 0;
}
.cateStyle {
  float: left;
}
.el-tag {
  margin: 10px;
}
</style>